from sqlalchemy.dialects.mysql import LONGTEXT
from app import db
from app.common.enums import PublishType

from .base_model import BaseModel

# # 文章-标签 多对的关系
tags = db.Table(
    'article_tag',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id', ondelete='cascade'), primary_key=True, comment='标签ID'),
    db.Column('article_id', db.Integer, db.ForeignKey('article.id', ondelete='cascade'), primary_key=True,
              comment='文章ID'),
    comment='文章标签关联表'
)


class Article(BaseModel):
    """文章"""
    __tablename__ = 'article'
    __table_args__ = ({'comment': '文章记录表'})
    id = db.Column(db.Integer, primary_key=True, comment="文章ID")
    title = db.Column(db.String(255), nullable=False, comment="文章标题")
    description = db.Column(db.String(255), nullable=True, comment="文章描述")
    content = db.Column(LONGTEXT, nullable=False, comment="文章内容")
    # 使用枚举类型
    has_type = db.Column(db.Enum(PublishType), server_default='show', nullable=False, comment="文章状态")
    # 外键分类ID
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=True, comment="文章分类ID")
    # 创建Tag关联
    tags = db.relationship(
        'Tag',
        secondary=tags,
        lazy='subquery',
        backref=db.backref('article', lazy='dynamic'),
        passive_deletes=True
    )

    def __repr__(self) -> str:
        return "<Article %s>" % self.to_json()
